const express = require('express')
const router = express.Router()
const fs = require("fs");
const multer  = require('multer')
const config = require('../Config')
const qiniu = require('qiniu');


const mac = new qiniu.auth.digest.Mac(config.qiniuConfig.AccessKey, config.qiniuConfig.SecretKey);
const putExtra = new qiniu.form_up.PutExtra();

const options = {
  scope: config.qiniuConfig.Bucket,
  returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
};

const putPolicy = new qiniu.rs.PutPolicy(options)

var upload = multer({dest: 'public/uploads/'});

router.post('/article',upload.single('editormd-image-file'),function(req,res){
  var file = req.file;
  let ret = {};
 
  var file = req.file;
  if (file) {
      var fileNameArr = file.originalname.split('.');
      var suffix = fileNameArr[fileNameArr.length - 1];
      //文件重命名
      fs.renameSync('./public/uploads/' + file.filename, `./public/uploads/${file.filename}.${suffix}`);
      file['newfilename'] = `${file.filename}.${suffix}`;
      ret['success'] = 1;
      ret['url']= `//${req.hostname}:3000/public/uploads/${file.filename}.${suffix}`;
  }
  //ret['file'] = file;
  
    // console.log('文件类型：%s', file.mimetype);
    // console.log('原始文件名：%s', file.originalname);
    // console.log('文件大小：%s', file.size);
    // console.log('文件保存路径：%s', file.path);
    res.json(ret)
})

router.get('/getQiNiuToken',function(req,res){
  uploadToken = putPolicy.uploadToken(mac)
  if(uploadToken){
    res.json({
      code:0,
      uptoken:uploadToken,
      msg:'ok'
    })
  }

})







module.exports= router